﻿
<ValueConversion(GetType(String), GetType(Integer))>
Public Class CharCodeToIntegerConverter
    Inherits Markup.MarkupExtension
    Implements IValueConverter

    Public Sub New()
    End Sub

    Private Shared mConverter As CharCodeToIntegerConverter
    Public Overrides Function ProvideValue(serviceProvider As IServiceProvider) As Object
        If mConverter Is Nothing Then
            mConverter = New CharCodeToIntegerConverter
        End If
        Return mConverter
    End Function

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        Dim s As String = value.ToString
        Dim val As Integer
        If Integer.TryParse(s, val) Then
            Return val
        Else
            If s.Length = 3 AndAlso s.StartsWith("'") AndAlso s.EndsWith("'") Then
                Return System.Convert.ToInt32(s(1))
            Else
                Return 0
            End If
        End If
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Dim ascii As Integer = CInt(value)
        Dim ch As Char = System.Convert.ToChar(CInt(ascii))
        If Char.IsControl(ch) OrElse ascii > 127 Then
            'Non-printable ascii returns the ascii number
            Return ascii.ToString
        Else
            'printable ascii returns in the form 'x'
            Return "'" & ch & "'"
        End If
    End Function

End Class
